﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;

namespace MG_POS_PC.Util
{
    public class iniUtil
    {

        private static string filename = System.Environment.CurrentDirectory + "\\" + FileName.iniConfig;
        private static string area ;
        private static string DataSource;
        private static string InitialCatalog;
        private static string IntegratedSecurity;



        public static void loadIni()
        {
            area = System.IO.Path.GetFileNameWithoutExtension(filename);

            if (File.Exists(filename))
            {
                 DataSource = ContentReader(area, "Data Source", "");
                 InitialCatalog = ContentReader(area, "Initial Catalog", "");
                 IntegratedSecurity = ContentReader(area, "Integrated Security", "");
            }
        }

        private static void writeLog(string mess)
        {
            FileStream fs = new FileStream(@"c:/mcWindowsService.txt", FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter m_streamWriter = new StreamWriter(fs);
            m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
            m_streamWriter.WriteLine(" -->" + mess);
            m_streamWriter.Flush();
            m_streamWriter.Close();
            fs.Close();
        }

        public static void updateIni(string filename, string dataSource, string initialCatalog, string integratedSecurity)
        {
            if (File.Exists(filename))
            {
                WritePrivateProfileString(area, "Data Source", dataSource, filename);
                WritePrivateProfileString(area, "Initial Catalog", initialCatalog, filename);
                WritePrivateProfileString(area, "Integrated Security", integratedSecurity, filename);
            }
        }


        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(
            string lpAppName,
            string lpKeyName,
            string lpDefault,
            StringBuilder lpReturnedString,
            int nSize,
            string lpFileName);

        public static string ContentReader(string area, string key, string def)
        {
            StringBuilder stringBuilder = new StringBuilder(1024);
            GetPrivateProfileString(area, key, def, stringBuilder, 1024, filename);
            return stringBuilder.ToString();
        }

        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(
            string mpAppName,
            string mpKeyName,
            string mpDefault,
            string mpFileName);
    }
}
